package hong.jdbc;

import java.sql.*;

public class JdbcUtil {


    //执行查询语句
    public static void executeQuery(String sql, Object... params) throws Exception {

        PreparedStatement statement = getConnection().prepareStatement(sql);
        for (int i = 0; params != null && i < params.length; i++) {
            statement.setObject(i + 1, params[i]);
        }
        ResultSet resultSet = statement.executeQuery();
        while (resultSet.next()) {
            String id = resultSet.getString("id");
            String name = resultSet.getString("name");
            String age = resultSet.getString("age");
            String birthday = resultSet.getString("birthday");
            System.out.println("id=" + id + "  name=" + name + "   age=" + age + "  birthday=" + birthday);
        }
        close(resultSet);
        close(statement);

    }


    public static int executeUpdate(String sql, Object... params) throws Exception {

        PreparedStatement statement = getConnection().prepareStatement(sql);
        for (int i = 0; params != null && i < params.length; i++) {
            statement.setObject(i + 1, params[i]);
        }
        int res = statement.executeUpdate();
        close(statement);
        return res;

    }

    private static Connection getConnection() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");//找到oracle驱动器所在的类
        String url = "jdbc:mysql://@106.12.95.23:1521/test"; //URL地址
        String username = "scott";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, username, password);
        return connection;
    }


    private static void close(PreparedStatement statement) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    private static void close(ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


}
